package com.example.gustavo.hello.task;

import android.util.Log;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

/**
 * 任务管理类
 *
 * 如果需要把任务添加到任务队列后并立即执行，则用startMsgTask方法，结束这个任务时要用stopMsgTask方法，如果没有这个任务 stopMsgTask返回false；
 如果需要把任务添加到任务队列但不确定什么时候执行，则用putMsgTask方法，结束这个任务时就用removeMsgTask方法就可以了，如果没有这个任务removeMsgTask返回null。
 * Created by gustavo on 2015/1/5.
 */
public class MsgManager {
    private static Timer timer = new Timer();
    private static Map<MsgKey, MsgTask> msgTasks = Collections
            .synchronizedMap(new HashMap<MsgKey, MsgTask>());

    public static void putMsgTask(MsgKey msgKey,
                                  MsgTask msgTask) {
        synchronized (msgTasks) {
            msgTasks.put(msgKey, msgTask);
        }
    }

    public static void startMsgTask(MsgKey msgKey,
                                    MsgTask msgTask) {
        putMsgTask(msgKey, msgTask);
        timer.schedule(msgTask, msgTask.getDeltaTime());
        Log.d("zyr", "" + msgKey.getIndex());
    }

    public static MsgTask removeMsgTask(MsgKey msgKey) {
        MsgTask msgTask = null;
        synchronized (msgTasks) {
            msgTask = msgTasks.remove(msgKey);
        }
        return msgTask;
    }

    public static boolean stopMsgTask(MsgKey msgKey) {
        MsgTask msgTask = removeMsgTask(msgKey);
        if(msgTask != null)
        {
            msgTask.cancel();
            return true;
        }
        return false;
    }

}